﻿using ConfExpert;
using ConfExpert.Entities;
using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using ConfOrderDS;
using ConfOrderDS.AppDSTableAdapters;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPivotGrid;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;

namespace ConfOrder
{
    public partial class XForm : DevExpress.XtraEditors.XtraForm
    {
        int WhoAmI = -1;
        int MyDept = -1;

        public AppDS ds = null;

        public Image notready = Properties.Resources.NotReadySmall;
        string adet = "Count: ";
        string toplam = "Sum: ";

        public XForm()
        {
            InitializeComponent();


            if (AppSession.UserInfo != null)
            {
                WhoAmI = AppSession.UserInfo.UserId;
                MyDept = AppSession.UserInfo.DeptId;
            }

            this.StartPosition = FormStartPosition.CenterParent;

            //BaseBarManager = barManager;

            ds = new AppDS();
            ds.EnforceConstraints = false;

            foreach (DataRelation rel in ds.Relations)
            {
                ForeignKeyConstraint ParentFK = new ForeignKeyConstraint(rel.ParentColumns, rel.ChildColumns);
                ParentFK.UpdateRule = Rule.Cascade;
                rel.ChildTable.Constraints.Add(ParentFK);
            }

            TAM = new TableAdapterManager();

        }

        public RepositoryItemCheckedComboBoxEdit riVisibility = new RepositoryItemCheckedComboBoxEdit();

        public void ExecQuery(string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                AppSession.DataManager.ExecuteNonQuery(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }


        void gridview_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {

            GridView g = sender as GridView;
            DevExpress.XtraGrid.Views.Base.GridCell[] cells = g.GetSelectedCells();
            if (cells.Length == 0)
                return;

            double sum = 0;

            foreach (DevExpress.XtraGrid.Views.Base.GridCell gc in cells)
            {
                double val = 0.0;
                string cellVal = g.GetRowCellDisplayText(gc.RowHandle, gc.Column);
                CultureInfo ci = Application.CurrentCulture;
                double.TryParse(cellVal, NumberStyles.Any, ci, out val);

                sum += val;
            }

            adet = string.Format("{0}{1:n0}", "Count: ", cells.Length);

            if (sum > 0)
                toplam = string.Format("{0}{1:n1}", "Sum: ", sum);
            else
                toplam = "";

            AppSession.MainForm.NotifySelectionInfo(this);
        }
        string selectionInfo = "";
        public string SelectionInfo
        {
            get
            {

                string seperator = "  " + ((char)183) + "  ";
                List<string> result = new List<string>();

                result.Add(adet);

                if (toplam != "")
                    result.Add(toplam);

                if (selectionInfo != "")
                    result.Add(selectionInfo);

                return string.Join(seperator, result.ToArray());
            }
            set
            {
                selectionInfo = value;
                AppSession.MainForm.NotifySelectionInfo(this);
            }
        }


        public void gvAks_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            if (e.ListSourceRowIndex > -1)
                if (e.IsGetData)
                    if (e.Column.FieldName == "ScA")
                    {
                        int AksesuarId;

                        if (e.Row is PivotDrillDownDataRow)
                            AksesuarId = (((PivotDrillDownDataRow)e.Row)["AksesuarId"]).ToIntNN();
                        else
                            AksesuarId = (((DataRowView)e.Row)["AksesuarId"]).ToIntNN();

                        if (AksesuarId > 0)
                        {
                            AppDS.V_AksesuarRow ar = RepositoryManager.dsi.V_Aksesuar.FindByAksesuarId(AksesuarId);

                            if (ar != null)
                                if (!ar.IsPhotoMikroNull())
                                    e.Value = ar.PhotoMikro;
                        }
                    }
                    else if (";BrandId;ProductCategoryId;Renk;Boy;Etiket;Aciklama;AksSeriId;".Contains(";" + e.Column.FieldName + ";"))
                    {
                        int AksesuarId = (((DataRowView)e.Row)["AksesuarId"]).ToIntNN();
                        if (AksesuarId > 0)
                        {
                            AppDS.V_AksesuarRow ar = RepositoryManager.dsi.V_Aksesuar.FindByAksesuarId(AksesuarId);
                            if (ar != null)
                                //switch (e.Column.FieldName)
                                //{
                                //    case "KDV":
                                //        ConfExpert.Datasets.MyData.ProductCategoryRow cr = RepositoryManager.dsi.ProductCategory.FindByProductCategoryId(ar["ProductCategoryId"].ToInt(-1));
                                //        if (cr != null)
                                //            e.Value = cr["KDV"];
                                //        break;

                                //    default:
                                e.Value = ar[e.Column.FieldName];
                            //        break;
                            //}
                            //else
                            //    e.Value = "";
                        }

                    }
        }

        public void AksesuarAlanlariEkle(GridView gv)
        {
            //gv.GridControl.ForceInitialize();
            int idx = gv.Columns["AksesuarId"].VisibleIndex;
            //MyAddField(gv, "BrandId", ref idx, RI(Rp.Brand));
            MyAddField(gv, "ProductCategoryId", ref idx, RI(Rp.ProductCategory));
            MyAddField(gv, "Renk", ref idx);
            MyAddField(gv, "Boy", ref idx);
            MyAddField(gv, "Etiket", ref idx);
            MyAddField(gv, "Aciklama", ref idx);
            MyAddField(gv, "AksSeriId", ref idx);
        }


        public void MyAddField(GridView gv, string FieldName, ref int idx, params object[] ri)
        {
            GridColumn unb = gv.Columns.AddField(FieldName);
            unb.UnboundType = DevExpress.Data.UnboundColumnType.String;
            //unbColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //unbColumn.DisplayFormat.FormatString = "c";
            //unb.AppearanceCell.BackColor = Color.LemonChiffon;
            unb.OptionsColumn.AllowEdit = false;
            unb.VisibleIndex = ++idx;

            if (FieldName == "AksSeriId")
                unb.Caption = "SeriId";

            if (ri.Length > 0)
                unb.ColumnEdit = ri[0] as RepositoryItemGridLookUpEdit;

            unb.FilterMode = ColumnFilterMode.DisplayText;
            gv.Columns.Add(unb);
        }


        public void InitGridView(GridView gridview, BindingSource bs, bool initialized = false)
        {
            string lastColName = "";

            try
            {
                gridview.GridControl.MenuManager = barManager;
                gridview.SelectionChanged -= gridview_SelectionChanged;
                gridview.SelectionChanged += gridview_SelectionChanged;
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                if (bs != null)
                {
                    gridview.GridControl.DataSource = null;
                    gridview.GridControl.DataSource = bs;
                    gridview.PopulateColumns();
                }
                if (gridview.ViewCaption == string.Empty)
                    gridview.ViewCaption = gridview.Name;

                bool containsProduct = gridview.Columns.Contains(gridview.Columns["ProductId"]);
                bool containsAksesuar = gridview.Columns.Contains(gridview.Columns["AksesuarId"]);

                foreach (GridColumn col in gridview.Columns)
                {
                    lastColName = col.FieldName;
                    if (lastColName != bs.DataMember + "Id")
                        MapGridColumn(col);
                    else
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.AppearanceCell.BackColor = System.Drawing.Color.LightYellow;
                    }

                    if (col.ColumnType == Type.GetType("System.Boolean"))
                    {
                        RepositoryItemCheckEdit ri = new RepositoryItemCheckEdit();
                        ri.AllowGrayed = false;
                        col.ColumnEdit = ri;
                    }
                    else if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }
                    else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;
                }
                if (containsProduct)
                {
                    GridColumn colPhoto = new GridColumn();
                    if (gridview.GetType() == typeof(BandedGridView))
                        colPhoto = new BandedGridColumn();

                    colPhoto.ToolTip = 
                    colPhoto.FieldName = "Scan";
                    colPhoto.Caption = "S";
                    gridview.Columns.Add(colPhoto);

                    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
                    CenterGridColumn(colPhoto);

                    gridview.CustomUnboundColumnData -= new CustomColumnDataEventHandler(gvProduct_CustomUnboundColumnData);
                    gridview.RowCellClick -= new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove -= new MouseEventHandler(gridview_MouseMove);

                    gridview.CustomUnboundColumnData += new CustomColumnDataEventHandler(gvProduct_CustomUnboundColumnData);
                    gridview.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove += new MouseEventHandler(gridview_MouseMove);

                    List<string> visibleColumnNames = new List<string>();
                    foreach (GridColumn gc in gridview.Columns)
                        if (gc.Visible)
                            visibleColumnNames.Add(gc.FieldName);

                    foreach (GridColumn gc in gridview.Columns)
                        gc.VisibleIndex = -1;

                    int k = -1;
                    if (gridview.GetType() == typeof(BandedGridView))
                        k++;

                    if (visibleColumnNames.Contains("ProductId"))
                    {
                        int scanIndex = visibleColumnNames.IndexOf("ProductId");
                        visibleColumnNames.Insert(scanIndex, "Scan");
                    }
                    else if (gridview.Columns["Scan"] != null)
                        visibleColumnNames.Insert(0, "Scan");

                    foreach (string colName in visibleColumnNames)
                    {
                        GridColumn col = gridview.Columns[colName];
                        k++;
                        col.VisibleIndex = k;
                    }

                    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);

                    gridview.CustomDrawCell -= new RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    gridview.CustomDrawCell += new RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                }
                else if (containsAksesuar)
                {
                    if (gridview.Columns.Contains(gridview.Columns["AksesuarId"]))
                        AksesuarAlanlariEkle(gridview);

                    GridColumn colPhoto = new GridColumn();
                    if (gridview.GetType() == typeof(DevExpress.XtraGrid.Views.BandedGrid.BandedGridView))
                        colPhoto = new DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn();

                    colPhoto.FieldName = "ScA";
                    gridview.Columns.Add(colPhoto);

                    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
                    CenterGridColumn(colPhoto);

                    gridview.CustomUnboundColumnData -= new CustomColumnDataEventHandler(gvAks_CustomUnboundColumnData);
                    gridview.RowCellClick -= new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove -= new MouseEventHandler(gridview_MouseMove);

                    gridview.CustomUnboundColumnData += new CustomColumnDataEventHandler(gvAks_CustomUnboundColumnData);
                    gridview.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove += new MouseEventHandler(gridview_MouseMove);

                    Dictionary<string, int> visibleColumnNames = new Dictionary<string, int>();
                    foreach (GridColumn gc in gridview.Columns)
                        if (gc.Visible)
                            visibleColumnNames.Add(gc.FieldName, gc.VisibleIndex);

                    foreach (GridColumn gc in gridview.Columns)
                        gc.VisibleIndex = -1;

                    int k = -1;
                    if (gridview.GetType() == typeof(BandedGridView))
                        k++;

                    if (visibleColumnNames.ContainsKey("AksesuarId"))
                    {
                        int scanIndex = visibleColumnNames.FirstOrDefault(x => x.Key == "AksesuarId").Value.ToIntNN();
                        visibleColumnNames.Add("ScA", scanIndex);
                    }
                    else if (gridview.Columns["ScA"] != null)
                        visibleColumnNames.Add("ScA", 0);

                    foreach (KeyValuePair<string, int> colName in visibleColumnNames)
                    {
                        int visibleIndex = k == -1 ? colName.Value : colName.Value + 1;
                        GridColumn col = gridview.Columns[colName.Key];
                        col.VisibleIndex = visibleIndex;
                    }

                    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell -= new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                }

                gridview.BestFitMaxRowCount = 50;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                gridview.NewItemRowText = "Click to add new row";
                gridview.OptionsClipboard.CopyColumnHeaders = DefaultBoolean.False;
                gridview.OptionsBehavior.EditorShowMode = AppSession.Settings.EditorShowMode;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.EnableAppearanceOddRow = true;

                //gridview.OptionsView.EnableAppearanceEvenRow = AppSession.Settings.EnableAppearanceEvenRow;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }
                GridManager.GetManager(gridview);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }
        }

        void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName == "Scan" || e.Column.FieldName == "PhotoMikro") &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 16), e.Bounds.Y);
                    e.Handled = true;
                }
        }

        void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle > -1)
                e.RowHeight = 28;

            if (e.RowHeight < notready.Height)
                e.RowHeight = notready.Height;
        }

        public void MapGridColumn(GridColumn col)
        {
            string fieldName = col.FieldName;

            col.FilterMode = ColumnFilterMode.DisplayText;
            //You can change the filter condition in the OptionsColumn.AutoFilterCondition property for every column in GridView.
            //col.OptionsFilter.AutoFilterCondition = (AppSession.Settings.PopupFilterMode == PopupFilterMode.Contains ? AutoFilterCondition.Contains : AutoFilterCondition.Default);    // AutoFilterCondition.Contains;

            col.OptionsColumn.AllowEdit = col.FieldName != "UserId";    //userId sonradan değiştirilemesin diye!

            RepositoryItem ri = GetFieldRI(fieldName);
            if (ri != null)
                col.ColumnEdit = ri;
            else if (col.ColumnType == typeof(String))
                col.ColumnEdit = new RepositoryItemTextEdit();

            switch (fieldName)
            {
                case "photo":
                case "photo0":
                case "photo1":
                case "photo2":
                case "photo3":
                case "photomikro":
                case "photolarge":
                    CenterGridColumn(col);
                    break;

                case "deleted":
                case "temp":
                case "ınsertedon":
                case "modifiedon":
                case "ts": col.Visible = false; break;

                case "en": col.FormatAsNumber(0); break;

                default:
                    if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(0);
                    else if (";fiyat;hedeffiyat;anlasilanfiyat;xanlasilanfiyat;faturafiyati;xfaturafiyati;birimfiyat;unitprice;latestunitprice;price;price_;cost;balance;linetotal;subtotal;discount;grandtotal;taxamt;freight;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(2);

                    break;
            }
        }

        public void gvProduct_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.ListSourceRowIndex > -1 && e.Column.FieldName == "Scan")
                if (e.IsGetData)
                {
                    int ProductId = (((DataRowView)e.Row)["ProductId"]).ToIntNN();
                    if (ProductId > 0)
                    {
                        AppDS.V_KumasRow ar = RepositoryManager.dsi.V_Kumas.FindByProductId(ProductId);

                        if (ar != null)
                            if (!ar.IsPhotoMikroNull())
                                e.Value = ar.PhotoMikro;
                    }
                }
        }

        void gridview_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Scan")
                {
                    int productId = GetProductId(view, e.RowHandle);
                    if (productId > 0)
                        Goster(productId);
                }
                else if (e.Column.FieldName == "ScA")
                {
                    int aksesuarId = GetAksesuarId(view, e.RowHandle);
                    if (aksesuarId > 0)
                        GosterA(aksesuarId);

                }
            }
        }

        public void GosterA(int AksesuarId)
        {
            GosterBaseA(AksesuarId);
        }

        private static void GosterBaseA(int AksesuarId)
        {
            if (AksesuarId > 0)
            {
                //Notify("Please wait while fetching fabric image...");
                Cursor.Current = Cursors.WaitCursor;

                using (DetailA dv = new DetailA(AksesuarId))
                    dv.ShowDialog();

                GC.Collect();

                Cursor.Current = Cursors.Default;
            }
        }

        private int GetAksesuarId(GridView gv, int rowHandle)
        {
            int aksesuarId = gv.GetDataRow(rowHandle)["AksesuarId"].ToIntNN();
            return aksesuarId;
        }


        void gridview_MouseMove(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo info = view.CalcHitInfo(new Point(e.X, e.Y));

            if (info.InRowCell && info.Column.FieldName == "Scan" && info.RowHandle > -1)
            {
                int productId = GetProductId(view, info.RowHandle);
                if (productId > 0)
                    view.GridControl.Cursor = Cursors.Hand;
            }
            else if (info.InRowCell && info.Column.FieldName == "ScA" && info.RowHandle > -1)
            {
                int aksesuarId = GetAksesuarId(view, info.RowHandle);
                if (aksesuarId > 0)
                    view.GridControl.Cursor = Cursors.Hand;
            }
            else
                view.GridControl.Cursor = Cursors.Default;
        }

        private int GetProductId(GridView gv, int rowHandle)
        {
            int productId = gv.GetDataRow(rowHandle)["ProductId"].ToIntNN();
            return productId;
        }

        public void Goster(int ProductId)
        {
            GosterBase(ProductId);
        }

        private static void GosterBase(int ProductId)
        {
            //Notify("Please wait while fetching fabric image...");
            Cursor.Current = Cursors.WaitCursor;

            ProductViewer pv = new ProductViewer(ProductId);
            using (pv)
            {
                pv.ShowDialog();
            }
            GC.Collect();

            Cursor.Current = Cursors.Default;
        }

        public void CenterGridColumn(GridColumn col)
        {
            col.AppearanceCell.Options.UseTextOptions = true;
            col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
        }

        public RepositoryItem RI(Rp repository)
        {
            return RepositoryManager.Get(repository);
        }

        public RepositoryItem GetFieldRI(string fieldName)
        {

            fieldName = fieldName.ToLower();

            if (fieldName.EndsWith("Id".ToLower()))
            {
                fieldName = fieldName
                                        .Substring(0, fieldName.Length - 2)
                                        .Replace("latest", "")
                                        .Replace("prf", "");
                switch (fieldName)
                {
                    case "cari": return RI(Rp.Cari);
                    case "kaynak": return RI(Rp.Kaynak);
                    case "addresstype": return RI(Rp.AddressType);

                    case "atelye":
                    case "cikisyeri": return RI(Rp.Atelye);

                    case "belgetipi":
                    case "belgetipialis": return RI(Rp.BelgeTipiAlis);
                    case "belgetipisatis": return RI(Rp.BelgeTipiSatis);
                    case "carrier": return RI(Rp.Carrier);
                    case "contacttype": return RI(Rp.ContactType);
                    case "country": return RI(Rp.Country);

                    case "currency":
                    case "hedefcurrency":
                    case "dvz":
                    case "xdvz":
                    case "faturadvz":
                    case "xfaturadvz":
                    case "dovizcinsi": return RI(Rp.Currency);

                    case "culture": return RI(Rp.Culture);
                    case "origin": return RI(Rp.Origin);


                    case "teslimseklis": return RI(Rp.TeslimSekliS);
                    case "department": return RI(Rp.Department);

                    case "sender":
                    case "user":
                    case "cikanuser":
                    case "cikan":
                    case "employee":
                    case "duzenleyen":
                    case "talepeden":
                    case "talebiacan":
                    case "sipveren":
                    case "siparişeden":
                    case "sipariseden":
                    case "sorumlu":
                    case "olusturan":
                    case "onaylayan":
                    case "planlamaci":
                    case "odeyen": return RI(Rp.V_User);

                    case "gruppotex": return RI(Rp.GruppoTex);

                    case "giristipi":
                    case "cikistipi":
                    case "harekettipi": return RI(Rp.HareketTipi);

                    case "depo": return RI(Rp.Depo);
                    case "model": return RI(Rp.Model);
                    case "module": return RI(Rp.Module);

                    case "marka":
                    case "brand":
                    case "newbrand":
                    case "onaylayacak": return RI(Rp.Brand);

                    case "paymentterm": return RI(Rp.PaymentTerm);
                    case "paymentmethod": return RI(Rp.PaymentMethodA);
                    case "paymentmethoda": return RI(Rp.PaymentMethodA);
                    case "paymentmethods": return RI(Rp.PaymentMethodS);
                    case "productcategory": return RI(Rp.ProductCategory);

                    case "product":
                    case "product1":
                    case "product2":
                    case "product3":
                    case "product4":
                    case "subst":
                    case "subst1":
                    case "subst2":
                    case "subst3":
                    case "alt":
                    case "org":
                    case "alternatif":
                    case "silinecek":
                    case "kalacak":
                    case "esp":
                    case "kumas": return RI(Rp.V_Kumas);

                    case "aksesuar": return RI(Rp.V_Aksesuar);
                    case "tela": return RI(Rp.Tela);
                    case "telavendor": return RI(Rp.TelaVendor);
                    case "telacins": return RI(Rp.TelaCins);
                    case "telafinish": return RI(Rp.TelaFinish);
                    case "raporboyu": return RI(Rp.RaporBoyu);

                    case "mt":
                    case "musteritemsilcisi":
                    case "sezon":
                    case "newsezon": return RI(Rp.Sezon);

                    case "reqshipmethod":
                    case "revshipmethod":
                    case "shipmethod": return RI(Rp.ShipMethod);

                    case "durum1":
                    case "sipdurumu1": return RI(Rp.SiparisDurumu1);

                    case "durum2":
                    case "sipdurumu2":
                    case "siparisdurumu": return RI(Rp.SiparisDurumu2);

                    case "yuklemesekli":
                    case "ongorulenyuklemesekli":
                    case "xongorulenyuklemesekli":
                    case "maxongorulenyuklemesekli":
                    case "gerceklesenyuklemesekli":
                    case "xgerceklesenyuklemesekli":
                    case "ongyuklemesekli":
                    case "revyuklemesekli":
                    case "teslimsekli":
                    case "ongteslimsekli":
                    case "gerteslimsekli":
                    case "faturadakiteslimsekli":
                    case "xteslimsekli":
                    case "xfaturadakiteslimsekli":
                    case "teslimseklia": return RI(Rp.TeslimSekliA);

                    case "deporaf":
                    case "stoktipi": return RI(Rp.StokTipi);
                    case "unitmeasure": return RI(Rp.UnitMeasure);

                    case "productionvendor":
                    case "latestvendor":
                    case "orgvendor":
                    case "kvendor":
                    //case "vendor":
                    case "tercihedilenuretici":
                    case "orjinaluretici":
                    case "uretici":
                    case "gelisyeri":
                    case "akstedarikci": return RI(Rp.Vendor);

                    case "kullanimyeri": return RI(Rp.KullanimYeri);
                    case "dagilim": return RI(Rp.Dagilim);
                    case "modelcategory": return RI(Rp.ModelCategory);
                    case "modelsubcategory": return RI(Rp.ModelSubcategory);
                    case "kalite": return RI(Rp.Kalite);
                    case "sttalep": return RI(Rp.stTalep);
                    case "taleptipi": return RepositoryManager.riTalepTipi;
                    case "stsiparis": return RI(Rp.stSiparis);
                    case "stcikis": return RI(Rp.stCikis);
                    case "stfatura": return RI(Rp.stFatura);
                    //case "stgenel": return RI(Rp.stGenel); TODO: 
                    case "sturetim": return RI(Rp.stUretim);
                    case "stkesim": return RI(Rp.stKesim);
                    case "engrubu": return RI(Rp.EnGrubu);
                    case "finish": return RI(Rp.Finish);

                    case "zeminrengi":
                    case "desenrengi": return RI(Rp.TemelRenk);

                    case "desen": return RI(Rp.Desen);
                    case "orgu": return RI(Rp.Orgu);
                    case "desenyonu": return RI(Rp.DesenYonu);
                    case "stokgrup": return RI(Rp.StokGrup);
                    case "grup7c": return RI(Rp.Grup7C);
                    case "grupesp": return RI(Rp.GrupESP);
                    case "stgeribildirim": return RI(Rp.stGeriBildirim);
                    case "geribildirimıletituru": return RI(Rp.GeriBildirimIletiTuru);
                    case "stap": return RI(Rp.stAP);
                    case "apyuklemesekli": return RI(Rp.apYuklemeSekli);
                    case "apnavlunsekli": return RI(Rp.apNavlunSekli);
                    case "apakreditifturu": return RI(Rp.apAkreditifTuru);
                    case "apodemesuresigun": return RI(Rp.apOdemeSuresiGun);
                    case "kompozisyon": return RI(Rp.Kompozisyon);
                    case "ytalimat": return RI(Rp.YTalimat);

                    case "terms":
                    case "priceterm": return RI(Rp.PriceTerm);

                    case "scenario": return RI(Rp.Scenario);
                    case "fabrictype": return RI(Rp.FabricType);
                    case "hata": return RI(Rp.Hata);
                    case "kstcategory": return RI(Rp.KstCategory);

                    case "stirsaliye":
                    case "stırsaliye": return RI(Rp.stIrsaliye);

                    case "prdtree": return RI(Rp.PrdTree);
                    case "ckbatch": return RI(Rp.CKBatch);
                    case "kalitekontrol": return RI(Rp.KaliteKontrol);
                    case "kumashatatipi": return RI(Rp.KumasHataTipi);
                    case "sevkiyatci": return RI(Rp.Sevkiyatci);
                    default: return null;
                }
            }
            else
            {
                switch (fieldName)
                {
                    case "photomikro":
                        return RepositoryManager.GetPhotoRI();

                    default:
                        if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        {
                            return new RepositoryItemCalcEdit();
                        }
                        return null;
                }
            }
        }

        public void GetDetails(string SemiColonSeperatedTableNames, string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                AppDS dsNew = (AppDS)AppSession.DataManager.Fill(new AppDS(), SemiColonSeperatedTableNames, SP, prm);

                ds.Merge(dsNew, false, MissingSchemaAction.AddWithKey);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        public static void SetSplitterPosition(SplitContainerControl scc)
        {
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public virtual void MySizeChanged(object sender, EventArgs e)
        {
            //SplitContainerControl scc = ((SplitContainerControl)sender);
            //scc.SizeChanged -= sizeChanged;
            SetSplitterPosition(sender as SplitContainerControl);
            //scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public List<BindingSource> sources;
        public void EndEdits()
        {
            this.Validate();
            if (sources != null)
                foreach (BindingSource bs in sources)
                    bs.EndEdit();
        }

        public int ChangesSubmitted = 0;
        public TableAdapterManager TAM;
        public virtual void Save()
        {
            EndEdits();
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Notify("Saving...");

                if (ds.HasChanges())
                    ChangesSubmitted += TAM.UpdateAll(ds);
            }
            catch (DBConcurrencyException ex)
            {
                ConcurrencySolver cs = new ConcurrencySolver(ex.Row);
                DialogResult response = cs.ShowDialog();

                switch (response)
                {
                    case DialogResult.OK:
                        GetDetails(ex.Row.Table.TableName, "UpdConflict", cs.Sql);
                        try
                        {
                            Save();
                        }
                        catch (Exception saveEx)
                        {
                            LogManager.LogToDB(saveEx.Message, cs.Log + response.ToString());
                            throw saveEx;
                        }
                        LogManager.LogToDB("Concurrency Exception", cs.Log + response.ToString());
                        break;

                    case DialogResult.Cancel:
                        LogManager.LogToDB("Concurrency Exception", cs.Log + response.ToString());
                        throw new ApplicationException("Değişiklikler KAYDEDİLMEDİ !!!");
                }

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
                Notify(string.Empty);
            }
        }

        public static void Notify(string str)
        {
            ConfExpert.Utility.AppSession.MainForm.NotifyMain(str);
        }

        public static void ShowProductPhoto(int ProductId)
        {
            GosterBase(ProductId);
        }

        private void XForm_Load(object sender, EventArgs e)
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = false;

            this.FormClosing += new FormClosingEventHandler(XForm_FormClosing);
        }

        public virtual void XForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ds.Dispose();
        }


    }
}